<?php

namespace addons\epay\controller;

use addons\epay\library\QRCode;
use addons\epay\library\Service;
use addons\epay\library\Wechat;
use addons\third\model\Third;
use app\common\library\Auth;
use think\addons\Controller;
use think\Cookie;
use think\Response;
use think\Session;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Pay;

/**
 * API接口控制器
 *
 * @package addons\epay\controller
 */
class Api extends Controller
{

    protected $layout = 'default';
    protected $config = [];

    /**
     * 默认方法
     */
    public function index()
    {
        return;
    }

    /**
     * 外部提交
     */
    public function submit()
    {
        $this->request->filter('trim');
        $out_trade_no = $this->request->request("out_trade_no");
        $title = $this->request->request("title");
        $amount = $this->request->request('amount');
        $type = $this->request->request('type');
        $method = $this->request->request('method', 'web');
        $openid = $this->request->request('openid', '');
        $auth_code = $this->request->request('auth_code', '');
        $notifyurl = $this->request->request('notifyurl', '');
        $returnurl = $this->request->request('returnurl', '');

        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型错误");
        }

        $params = [
            'type'         => $type,
            'out_trade_no' => $out_trade_no,
            'title'        => $title,
            'amount'       => $amount,
            'method'       => $method,
            'openid'       => $openid,
            'auth_code'    => $auth_code,
            'notifyurl'    => $notifyurl,
            'returnurl'    => $returnurl,
        ];
        return Service::submitOrder($params);
    }

    /**
     * 微信支付(公众号支付&PC扫码支付)
     * @return string
     */
    public function wechat()
    {
        $config = Service::getConfig('wechat');

        $isWechat = stripos($this->request->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
        $isMobile = $this->request->isMobile();
        $this->view->assign("isWechat", $isWechat);
        $this->view->assign("isMobile", $isMobile);

        //发起PC支付(Scan支付)(PC扫码模式)
        if ($this->request->isAjax()) {
            $pay = Pay::wechat($config);
            $orderid = $this->request->post("orderid");
            try {
                $result = $pay->find($orderid);
                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                    $this->success("", "", ['status' => $result['trade_state']]);
                } else {
                    $this->error("查询失败");
                }
            } catch (GatewayException $e) {
                $this->error("查询失败");
            }
        }
        $orderData = Session::get("wechatorderdata");
        if (!$orderData)
            $orderData = Cookie::get("wechatorderdata");
        if (!$orderData) {
            $this->error("请求参数错误111");
        }
        if ($isWechat) {
            //发起公众号(jsapi支付),openid必须

            //如果没有openid，则自动去获取openid
            if (!isset($orderData['openid']) || !$orderData['openid']) {
                $orderData['openid'] = Service::getOpenid();
            }

            $orderData['method'] = 'mp';
            $type = 'jsapi';
            $payData = Service::submitOrder($orderData);
            if (!isset($payData['paySign'])) {
                $this->error("创建订单失败，请返回重试", "");
            }
        } else {
            $orderData['method'] = 'scan';
            $type = 'pc';
            $payData = Service::submitOrder($orderData);
            if (!isset($payData['code_url'])) {
                $this->error("创建订单失败，请返回重试", "");
            }
        }
        $this->view->assign("orderData", $orderData);
        $this->view->assign("payData", $payData);
        $this->view->assign("type", $type);

        $this->view->assign("title", "微信支付");
        return $this->view->fetch();
    }

    /**
     * 支付宝支付(PC扫码支付)
     * @return string
     */
    public function alipay()
    {
        $config = Service::getConfig('alipay');

        $isWechat = stripos($this->request->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
        $isMobile = $this->request->isMobile();
        $this->view->assign("isWechat", $isWechat);
        $this->view->assign("isMobile", $isMobile);

        if ($this->request->isAjax()) {
            $orderid = $this->request->post("orderid");
            $pay = Pay::alipay($config);
            try {
                $result = $pay->find($orderid);
                if ($result['code'] == '10000' && $result['trade_status'] == 'TRADE_SUCCESS') {
                    $this->success("", "", ['status' => $result['trade_status']]);
                } else {
                    $this->error("查询失败");
                }
            } catch (GatewayException $e) {
                $this->error("查询失败");
            }
        }

        //发起PC支付(Scan支付)(PC扫码模式)
        $orderData = Session::get("alipayorderdata");
        if (!$orderData) {
            $this->error("请求参数错误");
        }
		
        $orderData['method'] = 'scan';
        $payData = Service::submitOrder($orderData);
        if (!isset($payData['qr_code'])) {
            $this->error("创建订单失败，请返回重试");
        }

        $type = 'pc';
        $this->view->assign("orderData", $orderData);
        $this->view->assign("payData", $payData);
        $this->view->assign("type", $type);
        $this->view->assign("title", "支付宝支付");
        return $this->view->fetch();
    }

    /**
     * 支付成功回调
     */
    public function notifyx()
    {
        $type = $this->request->param('type');
        if (!Service::checkNotify($type)) {
            echo '签名错误';
            return;
        }
		$data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $xorder = \app\admin\model\Xorder::get(['order_no' => $out_trade_no]);
            if ($xorder) {
                $xorder->paystatus = 1;
				
				/* //考试宝自动发码
				$package = \app\admin\model\Package::get($xorder['sale_product_id']);
				$vn = $package && $package['platform_vn'] ? $package['platform_vn'] : '0';
				$ksbao = cmf_get_ksbao_sendcdk_param();
				$url = $ksbao['domain'] . $ksbao['sendcdk'];
				$param = [
					"agent_code"=>$ksbao['agent_code'],
					"secretKey"=>$ksbao['secretKey'],
					"trade_no"=>$xorder['order_no'],
					"username"=>$xorder['mobile'],
					"price"=>$xorder['total_amount']/100,
					"appename"=>$xorder['sale_en_name'],
					"vn"=>$vn,
				];
				$res = cmf_send_post($url,$param);
				$res_array = json_decode($res,true);
				
				if($res_array['code'] == 0){
					
					$cdk = $res_array['data'];
					$mobile = '';
					if($xorder) $mobile = $xorder['mobile'];
					if(!cmf_check_mobile($mobile)){
						//发码成功  但是短信发送失败
						$xorder->cdkstatus = 5;
					} 
					$config = get_addon_config('alisms');
					//var_dump($config);exit;
					$sign = $config['sign'];
					$template = $config['template']['sendCDK'];
					$param = ['code'=>$cdk];
					$alisms = new \addons\alisms\library\Alisms();
					$ret = $alisms->mobile($mobile)
						->template($template)
						->sign($sign)
						->param($param)
						->send();
						
					if ($ret) {
					// $this->success("发送成功,记得保存哦,否则CDK将不会有记录");
						//发码成功  短信发送成功
						//echo "发码成功  短信发送成功";
						$xorder->cdkstatus = 1;
					} else {
						//发码成功  但是短信发送失败
						$xorder->cdkstatus = 5;
					}
					$xorder->sendtime = time();
					$xorder->cdk = $cdk;
				}else{
					//发码失败
					$xorder->cdkstatus = $res_array['code'];
					$xorder->cdkmsg = $res_array['msg'];
				}  */
                $xorder->save();
            }
        } catch (Exception $e) {
        }
        echo $pay->success();
        //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
        //下面这句必须要执行,且在此之前不能有任何输出
        //echo "success";
        return;
    }

    /**
     * 支付成功返回
     */
    public function returnx()
    {
        $type = $this->request->param('type');
        if (Service::checkReturn($type)) {
            echo '签名错误';
            return;
        }

        //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
        $this->success("恭喜你！支付成功!", addon_url("epay/index/index"));

        return;
    }

    /**
     * 生成二维码
     */
    public function qrcode()
    {
        $text = $this->request->get('text', 'hello world');

        //如果有安装二维码插件，则调用插件的生成方法
        if (class_exists("\addons\qrcode\library\Service") && get_addon_info('qrcode')['state']) {
            $qrCode = \addons\qrcode\library\Service::qrcode(['text' => $text]);
            $response = Response::create()->header("Content-Type", "image/png");

            header('Content-Type: ' . $qrCode->getContentType());
            $response->content($qrCode->writeString());
            return $response;
        } else {
            $qr = QRCode::getMinimumQRCode($text);
            $im = $qr->createImage(8, 5);
            header("Content-type: image/png");
            imagepng($im);
            imagedestroy($im);
            return;
        }
    }
    /**
     * 微信小程序支付
    */
    public function miniPay(){
        $category_name = $this->request->param('category_name');   //栏目名称
	    $package_name = $this->request->param('package_name');   //班次名称
	    $openid = $this->request->param('openid');
	    $source = $this->request->request('source'); // 来源和归属,可选
	    $kf = $this->request->request('kf');
	    $type = $this->request->request('type'); // 支付类型：wechat,alipay
	    $method = $this->request->request('method'); // 支付方法：web、wap、app、scan、pos、mp, miniapp
	    $product_id = $this->request->request('product_id');  // 产品id
	    $en_name = $this->request->request('en_name'); // 科目名
	    $out_trade_no = date("YmdHis") . uniqid();
	    // 外部自定义的重定向
	    $redirect = $this->request->request('redirect');
	    $mobile = $this->request->request('mobile');
	    if (!$this->auth->id) {
		    if (empty($mobile) || (strlen($mobile) != 11)) {
			    $this->error('请填写手机号 ！');
		    }
	    }
	    if (!$type || !in_array($type, ['alipay', 'wechat'])) {
		    $this->error("支付类型不正确");
	    }
	    if (!$method || !in_array($method, ['web','wap','app','scan','pos','mp','miniapp'])) {
		    $this->error("支付方法不正确");
	    }
	    if (empty($product_id)) {
		    $this->error('缺少产品信息');
	    }
	    $packageObj = \app\admin\model\Package::get($product_id);
	    if (! $packageObj) {
		    $this->error('产品不存在');
	    }
	    $subjectObj = \app\admin\model\yexam\Subject::get(['en_name' => $en_name]);
	    if (! $subjectObj) {
		    $this->error('科目不存在');
	    }
	    $categoryObj = \app\common\model\Category::get($subjectObj->category_id);
	    if (! $categoryObj) {
		    $this->error('系统分类信息有误');
	    }
	    $subject_package_ids = explode(',', $subjectObj->package_ids);
	    if (! in_array($packageObj->id, $subject_package_ids)) {
		    $this->error('当前科目下的没有该产品');
	    }
	    // 实付金额
	    $amount = floatval($packageObj->price);
	    if (!$amount || $amount < 0) {
		    $this->error("支付金额必须大于0");
	    }
	    // 商品名
	    $title = sprintf('%s - %s', $subjectObj->short_name, $packageObj->package_name);
	    // 订单号
	    $order = \app\admin\model\Xorder::get(['order_no' => $out_trade_no]);
	    // 回调链接
	    $notifyurl = sprintf(
		    '%s/api/payment/notifyx/paytype/%s/out_trade_no/%s',
		    $this->request->root(true),
		    $type,
		    $out_trade_no
	    );
	    $returnurl = sprintf(
		    '%s/api/payment/returnx/paytype/%s/out_trade_no/%s/redirect/%s',
		    $this->request->root(true),
		    $type,
		    $out_trade_no,
		    $redirect
	    );
	    $cookieId = cookie('csmonline_cookieid');
	    $client = cmf_is_mobile() ? 'm' : 'pc';
	    $res = cmf_mobile_get_userId($mobile,'123456',$client,$source,$en_name,'',$cookieId);
	    if(!$res) $this->error('创建用户失败');
	    $user_id = $res ? $res : $this->auth->id;
	    if($user_id){
		    cmf_cookieId_set_userId($user_id,$cookieId);
		    cmf_userId_set_cookieId($user_id,$cookieId);
	    }
	    // 入库
	    $data = [
		    'total_amount'     => floatval($amount) * 100,
		    'actual_amount'     => floatval($amount) * 100,
		    'order_no'          => $out_trade_no,
		    'paytype'           => $type,
		    'title'             => $title,
		    'sale_en_name'      => $en_name,
		    'sale_product_id'   => $product_id,
		    'paymethod'         => $method,
		    'source'            => $source,
		    'kf'                => $kf,
		    'mobile'            => $mobile,
		    'user_id'           => $user_id,
		    'sessionid'         => $cookieId,
		    'otype'         	=> 1,
		    'payment_content'   => json_encode([
			    'notifyurl' => $notifyurl,
			    'returnurl' => $returnurl
		    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
	    ];
	    // Hook::listen('api_payment_begin', $data);
	    $xorder = new \app\admin\model\Xorder;
	    $xorder->data($data);
	    if (! $xorder->save()) {
		    $this->error('创建订单失败');
	    }
	    Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method,$openid);
	    $packageObj = \app\admin\model\Package::get($product_id);
	    $amount = floatval($packageObj->price);
	    $title = sprintf('%s - %s', $category_name, $package_name);
	    $params = [
		    'amount'=> $amount,
		    'orderid'=> $out_trade_no,
		    'type'=>"wechat",
		    'title'=> $title,
		    'notifyurl'=>"https://vip.niukewang.com/api/Payment/notifyx",
		    'returnurl'=>"https://vip.niukewang.com/index/user/xiangqing?out_trade_no=".$out_trade_no,
		    'method'=>"miniapp",
		    'openid'=> $openid,
		    'auth_code'=>"123456"
	    ];
	    return \addons\epay\library\Service::submitOrder($params);
    
    }
    

}
